﻿using System;
using System.Collections.Generic;
using System.IO;
using EnvDTE;
using VSIXUtilities.DataObjects;
using VSLangProj;
using Microsoft.VisualStudio.Shell.Interop;
using System.Linq;
using System.CodeDom.Compiler;
using System.CodeDom;

namespace VSIXUtilities.Helpers.Extensions
{
    public static class ProjectItemExtensions
    {
        public static prjBuildAction GetBuildAction(this ProjectItem ProjectItemInstance)
        {
            return (prjBuildAction)ProjectItemInstance.Properties.Item("BuildAction").Value;
        }

        public static string GetDocCommentNotation(this ProjectItem ProjectItemInstance)
        {
            return GeneralExtensions.GetDocCommentNotation(Path.GetExtension(ProjectItemInstance.Name));
        }

        public static uint GetItemId(this ProjectItem ProjectItemInstance)
        {
            uint uintResult;
            ProjectItemInstance.ContainingProject.ToIVsHierarchy().ParseCanonicalName(ProjectItemInstance.GetFullPath(), out uintResult);
            return uintResult;
        }

        public static IVsHierarchyWrapper ToIVsHierarchyWrapper(this ProjectItem ProjectItemInstance)
        {
            return new IVsHierarchyWrapper(ProjectItemInstance.ContainingProject.ToIVsHierarchy(), ProjectItemInstance.GetItemId());
        }

        public static string GetFullPath(this ProjectItem ProjectItemInstance)
        {
            return ProjectItemInstance.Properties.Item("FullPath").Value.ToString();
        }

        public static ICodeParser GetICodeParser(this ProjectItem ProjectItemInstance)
        {
            Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider;
            ((IVsProject)ProjectItemInstance.ContainingProject.ToIVsHierarchy()).GetItemContext(ProjectItemInstance.GetItemId(), out serviceProvider);
            return serviceProvider.GetICodeParser();
        }

        public static CodeCompileUnit GetCodeCompileUnit(this ProjectItem ProjectItemInstance)
        {
            CodeCompileUnit CodeCompileUnitResult = null;
            ICodeParser ICodeParserInstance = ProjectItemInstance.GetICodeParser();
            if (ICodeParserInstance != null)
            {
                using (StreamReader streamReader = new StreamReader(ProjectItemInstance.Document.FullName))
                {
                    CodeCompileUnitResult = ICodeParserInstance.Parse(streamReader);
                }
            }
            return CodeCompileUnitResult;
        }
    }
}
